/**
 * 认证相关脚本
 * 用于处理JWT token认证
 */

// 获取JWT token的函数
const getJwtToken = function() {
    // 这里可以调用登录接口获取token
    const loginRequest = {
        url: pm.environment.get('baseUrl') + '/api/account/login',
        method: 'POST',
        header: {
            'Content-Type': 'application/json'
        },
        body: {
            mode: 'raw',
            raw: JSON.stringify({
                username: 'testuser',
                password: 'testpassword'
            })
        }
    };

    pm.sendRequest(loginRequest, function (err, res) {
        if (err) {
            console.error('Login failed:', err);
            return;
        }

        if (res.code === 200) {
            const token = res.json().token;
            pm.environment.set('jwt_token', token);
            console.log('JWT token obtained successfully');
        }
    });
};

// 自动添加认证头
const addAuthorizationHeader = function() {
    const token = pm.environment.get('jwt_token') || pm.environment.get('authorization');

    if (token) {
        // 如果token不包含Bearer前缀，添加前缀
        const authHeader = token.startsWith('Bearer ') ? token : `Bearer ${token}`;

        // 检查是否已存在Authorization头
        const existingAuthHeader = pm.request.headers.find(header =>
            header.key.toLowerCase() === 'authorization'
        );

        if (existingAuthHeader) {
            existingAuthHeader.value = authHeader;
        } else {
            pm.request.headers.add({
                key: 'Authorization',
                value: authHeader
            });
        }

        console.log('Authorization header added');
    } else {
        console.warn('No authentication token found');
    }
};

// 验证token是否过期
const validateToken = function() {
    const token = pm.environment.get('jwt_token');
    if (!token) {
        console.warn('No token found');
        return false;
    }

    try {
        // 简单的JWT token解析（不验证签名）
        const parts = token.split('.');
        if (parts.length !== 3) {
            console.warn('Invalid token format');
            return false;
        }

        const payload = JSON.parse(atob(parts[1]));
        const now = Math.floor(Date.now() / 1000);

        if (payload.exp && payload.exp < now) {
            console.warn('Token has expired');
            return false;
        }

        console.log('Token is valid');
        return true;
    } catch (e) {
        console.error('Token validation failed:', e);
        return false;
    }
};

// 导出函数
module.exports = {
    getJwtToken,
    addAuthorizationHeader,
    validateToken
};